package com.globallogic.training.basics;

import java.util.*;

public class PrimeNumbers{

	private static final String WRONG_NUMBER = "Wrong integer number";
	
	private static void printPrimeNumbers(int number) {
		System.out.println("\nPrime numbers less or equal then " + number + ":");
		
		for (int primeNumberCandidate = number; primeNumberCandidate > 0; primeNumberCandidate--) {
			boolean notPrimeNumber = false;
			
			for (int devisor = primeNumberCandidate - 1; devisor > 1; devisor--) {
				if (primeNumberCandidate % devisor == 0) {
					notPrimeNumber = true;
					break;
				}
			}
			
			if (!notPrimeNumber) {
				System.out.println(primeNumberCandidate);
			}
		}
	}
	
	private static boolean isExitCode(char[] userCharacters) {
		boolean gotCharQ = false;
		
		for (char userCharacter : userCharacters) {	
			if ((userCharacter == 'q' || userCharacter == 'Q') && !gotCharQ) {
				gotCharQ = true;
			} else if (userCharacter == ' ') {
				continue;
			} else {
				return false;
			}
		}
		
		if (gotCharQ) {
			return true;
		}
		
		return false;
	}
	
	private static boolean checkInput(char[] userCharacters) {
		boolean gotCharOfNumber = false;
		boolean gotSpace = false;
		
		for (char userCharacter : userCharacters) {	

			if (userCharacter >= '0' && userCharacter <= '9' && !gotSpace) {
				gotCharOfNumber = true;
			} else if (userCharacter == ' ') {
				if(gotCharOfNumber) {
					gotSpace = true;
				}

				continue;
			} else {
				return false;
			}
		}
			
		return true;
	}
	
	private static int processInput(char[] userCharacters) {	
		int userNumber = 0;
			
		for (char userCharacter : userCharacters) {	
			if (userCharacter >= '0' && userCharacter <= '9') {
				userNumber = userNumber * 10 + ((int)userCharacter - (int)'0');
			} 
		}
		
		return userNumber;
	}
	
	public static void printWelcomeMessage() {
		System.out.println("\nThis program calculates prime numbers less or equal than an integer number");	
	}
	
	private static void interactWithUser() {
		Scanner input = new Scanner(System.in);

		while (true) {		
			System.out.print("\nEnter an integer number (or q to exit): ");
			
			String userInput = input.nextLine();
			
			char[] userCharacters = userInput.toCharArray();
			
			if (isExitCode(userCharacters)) {
				return;
			}
						
			if (!checkInput(userCharacters)) {
				System.out.println(WRONG_NUMBER);
				continue;
			}
			
			int userNumber = processInput(userCharacters);
			
			if (userNumber != 0) {	
				printPrimeNumbers(userNumber);
			}			
		}
	}
	
	public static void main(String[] args) {
		printWelcomeMessage();
		
		interactWithUser();
	}
}